package org.example.demo3.controller;
import org.example.demo3.common.Salt_Encryption;
import org.example.demo3.common.Salt_Encryption.*;

import org.example.demo3.common.Ajaxtext;
import org.example.demo3.common.Session;
import org.example.demo3.common.UserSessionID;
import org.example.demo3.info.Userinfo;
import org.example.demo3.info.Userinfo_plus;
import org.example.demo3.service.Userservice;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;

@RestController
@RequestMapping("/user")
public class Usercontroller {
//    用户注册
    @Resource
    private Userservice userservice;
    @RequestMapping("/reg")
    public Ajaxtext reg(Userinfo userinfo){
        userinfo.setPassword(Salt_Encryption.encryption(userinfo.getPassword()));
        System.out.println("555555555"+userinfo);
        int result=userservice.reg(userinfo);
        if(result==0){
            return Ajaxtext.fail("操作失败",result);
        }else {
            return Ajaxtext.success("注册成功",result);
        }
    }
//    用户登录
    @RequestMapping("/login")
    public Ajaxtext login (HttpServletRequest request,Userinfo input_userinfo){
        Userinfo userinfo=userservice.login(input_userinfo);
        if (userinfo==null){
            return Ajaxtext.fail("密码或用户名错误",-1);
        }
        if (Salt_Encryption.verify(input_userinfo.getPassword(),userinfo.getPassword())){
            HttpSession session=request.getSession(true);
            session.setAttribute(UserSessionID.usersession,userinfo);
            return Ajaxtext.success("登录成功",1);
        }
        return Ajaxtext.fail("密码或用户名错误",-1);
    }
//    获取用户信息
    @RequestMapping("/infor_user")
    public Ajaxtext infor_user(HttpServletRequest request){
        Userinfo userinfo= Session.getsession(request);
        Userinfo_plus userinfoPlus=new Userinfo_plus();
        userinfoPlus.setCount(userservice.infor_user(userinfo));
        userinfoPlus.setType_count(userservice.type_count(userinfo.getId()));
        if(userinfo==null){
            return Ajaxtext.fail("空指针异常",-1);
        }
        userinfoPlus.setUsername(userinfo.getUsername());
        if (userinfoPlus.getCount()>=0){
            return Ajaxtext.success("文章数量",userinfoPlus);
        }else {
            return Ajaxtext.fail("文章数量异常",-1);
        }
    }
    @RequestMapping("/log_out")
    public int log_out(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession(false);
        if (session!=null){
            session.invalidate();
            return 1;
        }
        return -1;
    }
}
